#
# messkit.nson
#
# Copyright 2006 Helsinki Institute for Information Technology (HIIT)
# and the authors.
#
# Authors: Ken Rimey <rimey@hiit.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

"""
A data interchange format inspired by JSON and based on netstrings

As compared with JSON, this format is less readable and slightly less
compact, while somewhat easier to program.  Its key advantage is that
it can handle binary data.

Each container or atom is encoded as a netstring, whose content
consists of a one-byte type code followed by the actual content
encoded in a type-specific manner.

For example, the integer 42 is encoded as "3:i42,".  The type code for
integers is "i", and in this case the netstring encodes the three-byte
string "i42".

The following table summarizes the type codes, the corresponding
Python types, the most closely related JSON types, and the
type-specific content encoding.

  Code  Python  JSON    Content
    a   list    array   sequence of values
    d   dict    object  sequence of alternating keys and values
    s   str     string  byte string (can be binary data)
    t   unicode string  UTF-8 encoded text
    i   int     number  42, -3, 0, etc.
    f   float   number  3.14, 1e+100, 0.0, etc.
    b   bool    bool    either 0 or 1
    z   None    null    empty
"""

from messkit.netstring import parse_netstring, split_netstrings

def _int(s):
    try:
        return int(s)
    except ValueError:
        return long(s)          # Python 2.2

#
# Netstring -> Python data
#

def decode(string):
    """
    Decode a netstring into Python data, possibly recursively.
    """
    s, k = parse_netstring(string)
    if s is None:
        raise ValueError, 'Incomplete netstring.'
    if k != len(string):
        raise ValueError, 'Found junk after netstring.'
    return decode_content(s)

def decode_content(string):
    """
    Finish decoding when the top-level netstring has already been decoded.

    It is often good to process the top-level framing of a message
    stream separately from the decoding of the individual messages.
    This function can be used to do the decoding after a frame has
    been split out using parse_netstring().
    """
    code = string[0]
    f = _decoders[code]
    return f(string)

def _decode_list(string):
    return map(decode_content, split_netstrings(string, 1))

def _decode_dict(string):
    plist = split_netstrings(string, 1)
    n = len(plist)
    assert n % 2 == 0
    result = {}
    for k in range(0, n, 2):
        key = decode_content(plist[k])
        value = decode_content(plist[k + 1])
        result[key] = value
    return result

def _decode_str(string):
    return string[1:]

def _decode_unicode(string):
    return string[1:].decode('utf-8')

def _decode_int(string):
    return _int(string[1:])

def _decode_float(string):
    return float(string[1:])

def _decode_bool(string):
    return bool(int(string[1:]))

def _decode_none(string):
    return None

_decoders = {
    'a': _decode_list,
    'd': _decode_dict,
    's': _decode_str,
    't': _decode_unicode,
    'i': _decode_int,
    'f': _decode_float,
    'b': _decode_bool,
    'z': _decode_none,
    }

#
# Python data -> netstring
#

def encode(x):
    """
    Encode Python data into a netstring.
    """
    return ''.join(_encode(x))

def _encode(x):
    f = _encoders[type(x)]
    content = f(x)
    return str(len(content)), ':', content, ','

def _encode_list(x):
    buf = ['a']
    for v in x:
        buf.extend(_encode(v))
    return ''.join(buf)

def _encode_dict(x):
    items = x.items()
    items.sort()
    buf = ['d']
    for k, v in items:
        buf.extend(_encode(k) + _encode(v))
    return ''.join(buf)

def _encode_str(x):
    return 's' + x

def _encode_unicode(x):
    return 't' + x.encode('utf-8')

def _encode_int(x):
    return 'i' + str(x)

def _encode_float(x):
    return 'f' + str(x)

def _encode_bool(x):
    return 'b' + str(int(x))

def _encode_none(x):
    return 'z'

_encoders = {
    list: _encode_list,
    tuple: _encode_list,
    dict: _encode_dict,
    str: _encode_str,
    unicode: _encode_unicode,
    int: _encode_int,
    long: _encode_int,
    float: _encode_float,
    bool: _encode_bool,
    type(None): _encode_none,
    }

#
# Tests
#

if __name__ == '__main__':
    test_data = [
        None,
        True,
        False,
        0.0,
        3.14,
        42,
        -79348743594758554897593454534,
        '',
        'foo',
        ''.join([chr(i) for i in range(256)]),
        u'',
        u'foo',
        #u'\N{GREEK CAPITAL LETTER OMEGA}',
        u'\u03a9', # GREEK CAPITAL LETTER OMEGA in hex notation
        [],
        [1, 2, 3],
        [[], [1], [1, 2]],
        [[[[[[[[[[]]]]]]]]]],
        {},
        {'color': 'red', 'numbers': [1, 2, 3]},
        {'animals': {'tall': 'giraffe', 'heavy': 'elephant'},
         'colors': {'warm': 'red', 'cool': 'blue'}},
        ]

    for x in test_data:
        assert decode(encode(x)) == x

    print 'OK'
